// 新增收藏按钮组件
import 'package:flutter/material.dart';
import 'package:flutter_liquid_glass/liquid_glass.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:sinosheets/utils/bus_utils.dart';
import 'package:sinosheets/utils/favorite/product_util.dart';
import 'package:sinosheets/utils/theme/style_utils.dart';

class ProductFavoriteBtn extends StatefulWidget {
  final Map productInfo;
  final bool isFlashSale;
  const ProductFavoriteBtn({super.key, required this.productInfo, this.isFlashSale = true});

  @override
  State<ProductFavoriteBtn> createState() => _ProductFavoriteBtnState();
}

class _ProductFavoriteBtnState extends State<ProductFavoriteBtn> {
  late Future<bool> _isFavoriteFuture;

  @override
  void initState() {
    super.initState();
    _isFavoriteFuture = _getFavorite();
  }

  Future<bool> _getFavorite() async {
    if (widget.isFlashSale) {
      return await ProductUtil.isFlashSaleProductFavorite(widget.productInfo['id'].toString());
    } else {
      return await ProductUtil.isNormalProductFavorite(widget.productInfo['id'].toString());
    }
  }

  Future<void> _toggleFavorite() async {
    if (widget.isFlashSale) {
      await ProductUtil.toggleFlashSaleProductFavorite(widget.productInfo as Map<String, dynamic>);
    } else {
      await ProductUtil.toggleNormalProductFavorite(widget.productInfo as Map<String, dynamic>);
    }
    bus.emit('favorite_product_changed');
    Get.back();
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<bool>(
      future: _isFavoriteFuture,
      builder: (context, snapshot) {
        final isFavorite = snapshot.data ?? false;
        return LiquidGlassButton(
          config: LiquidGlassConfig(
            baseColor: ColorUtils.themeColor,
            opacity: 0.3,
            blurAmount: 80,
            borderRadius: BorderRadius.circular(100.r),
          ),
          icon: isFavorite ? Icons.favorite : Icons.favorite_border,
          iconColor: isFavorite ? Colors.red : Colors.white,
          onPressed: _toggleFavorite,
        );
      },
    );
  }
}
